package com.weiyan.blog.exception;

import com.alibaba.fastjson.JSON;
import com.weiyan.blog.response.Result;
import com.weiyan.blog.response.ResultCode;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author misterWei
 * @create 2020年01月21号:15点44分
 * @mailbox mynameisweiyan@gmail.com
 *
 * 权限不足异常类重写
 */



@Component("customAccessDeniedHandler")
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {
        Throwable cause = authException.getCause();

        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            if(cause instanceof InvalidTokenException) {
                response.getWriter().write(JSON.toJSONString(new Result(ResultCode.UNAUTHORISE)));
            }else{
                response.getWriter().write(JSON.toJSONString(new Result(ResultCode.UNAUTHORISE)));

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
